//
//  VOLBookHouseViewController.m
//  Volver
//
//  Created by administrator on 14-10-15.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLBookHouseViewController.h"

#import "common.h"
#import "HTTPDefine.h"


#import "ASIHTTPRequest.h"
#import "JSONKit.h"
#import "CalendarViewController.h"
#import "MBProgressHUD.h"

#import "VOLAppDelegate.h"
#import "VOLDateCellModel.h"
#import "OrderForm.h"

@interface VOLBookHouseViewController ()
{
    JSONDecoder *jd;
    VOLAppDelegate *del;
    
    CalendarViewController *calendarVC;
    MBProgressHUD *HUD;
    
    //已被预订的日期数组
    NSMutableArray *bookedDate;
    OrderForm *orderForm;
    //入住天数
    int days;
    //预订按钮
    UIButton *bookBtn;
}

@end

@implementation VOLBookHouseViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.

    NSLog(@"houseID = %d",self.house.houseID);
    NSLog(@"housePrice = %.1f",self.house.housePrice);
#pragma mark 提醒：最多入住人数
    self.noticeLable.text = [NSString stringWithFormat:@"(最多%d位)",self.house.housePersons];
    //初始化对象
    jd = [[JSONDecoder alloc] init];
    bookedDate = [NSMutableArray array];
    del = kGetDel;
    
    orderForm = [[OrderForm alloc] init];
    orderForm.userID = del.currentUser.userID;
    orderForm.houseID = self.house.houseID;
    orderForm.status = 0;
    orderForm.isComment = 0;
    orderForm.personNum = 1;
    
    //设置标题
    self.title = @"预订房屋";
    //添加返回按钮
    addBackButton();
    
#pragma mark 设置加减按钮的tag
    self.subButton.tag = 50;
    self.addButton.tag = 51;
    
    self.subButton.enabled = NO;
    if (self.house.housePersons == 1) {
        self.addButton.enabled = NO;
    }
    
#pragma mark 设置各控件的状态以及字体颜色
    
    //设置整个界面的view的背影色为白色
    self.view.backgroundColor = [UIColor whiteColor];
    
    //设置tableview代理
    self.dateTableView.delegate = self;
    self.dateTableView.dataSource = self;
    
    //设置textField代理
    self.personNumField.delegate = self;
    
    //设置浅颜色label
    self.arriveLabel.textColor = kPriceLabelColor;
    self.leaveLabel.textColor = kPriceLabelColor;
    self.daysLabel.textColor = kPriceLabelColor;
    self.totalLabel.textColor = kPriceLabelColor;
    self.priceLabel.textColor = kThemeColor;
    
    //设置Button字体颜色
    [self.arriveButton setTitleColor:kThemeColor forState:UIControlStateNormal];
    [self.arriveButton setTitleColor:kBlackColor forState:UIControlStateHighlighted];
    
    [self.leaveButton setTitleColor:kThemeColor forState:UIControlStateNormal];
    [self.leaveButton setTitleColor:kBlackColor forState:UIControlStateHighlighted];
    
    
    
#pragma mark 设置控件初始内容
    //选择日期按钮
    [self.arriveButton setTitle:@"选择日期" forState:UIControlStateNormal];
    [self.leaveButton setTitle:@"选择日期" forState:UIControlStateNormal];
    
    //房客人数
    self.personNumField.text = @"1位房客";
    
#pragma mark 设置一开始隐藏的控件
    //房客人数
    self.daysLabel.hidden = YES;
    
    //价格View
    self.priceView.hidden = YES;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    //给tableView添加一个Header并隐藏(将高度设置为0)
    UILabel *noticeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    noticeLabel.text = @"您是第一个预订本房子的人哦~~";
    noticeLabel.textColor = kThemeColor;
    noticeLabel.textAlignment = NSTextAlignmentCenter;
    self.dateTableView.tableHeaderView = noticeLabel;

    
#pragma mark 添加预订按钮
    bookBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, kViewHeight - 44, kViewWidth, 44)];
    bookBtn.backgroundColor = [UIColor colorWithRed:1 green:90.0/255 blue:95.0/255 alpha:0.9];
    
    //添加预订动作
    [bookBtn addTarget:self action:@selector(book:) forControlEvents:UIControlEventTouchUpInside];
    
    [bookBtn setTitle:@"预订" forState:UIControlStateNormal];
    [bookBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [bookBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    
    [self.view addSubview:bookBtn];
    bookBtn.hidden = YES;
#pragma mark 给tableView添加footer
    self.dateTableView.tableFooterView = [[UILabel alloc] init];
    
    
#pragma mark 加载数据
    [self loadHouseBookedDate:self.house.houseID];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 加载房屋预订日期信息
-(void)loadHouseBookedDate:(int)houseID{
    NSString *urlstr = [NSString stringWithFormat:@"%@orderform/searchAllArriveDateAndLeaveDate?houseID=%d&currentTime=%f",kHTTPHome,self.house.houseID,kGetCurrentTime];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    request.delegate = self;
    [request startAsynchronous];
}



#pragma mark - 动作方法

#pragma mark 返回方法
-(void)goBack:(id)sender{
    back;
}
#pragma mark 预订
-(void)book:(id)sender{
//    NSLog(@"book");
    __block int isSubmit = 0;

    if (orderForm.arriveDate == 0||orderForm.leaveDate == 0) {
        return;
    }
    
    BOOL isBooked = YES;
    //检查日期是否与已预订的有重叠
    for (VOLDateCellModel *model in bookedDate) {
        if (orderForm.arriveDate < model.arriveDate) {
            if (orderForm.leaveDate > model.arriveDate) {
                isBooked = NO;
                break;
            }
        }else{
            if (orderForm.arriveDate < model.leaveDate) {
                isBooked = NO;
                break;
            }
        }
    }
    if (!isBooked) {//不可预订时提醒
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"您所选的日期与已预订日期中有冲突，请重新选择!" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    //上传
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    
    HUD.labelText = @"预订中...";
    [HUD showAnimated:YES whileExecutingBlock:^{
        isSubmit = [self submitOrderForm:orderForm];
    } completionBlock:^{
        [HUD removeFromSuperview];
        HUD = nil;
        
        HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        
        if (isSubmit) {
            HUD.labelText = @"预订成功";
            HUD.mode = MBProgressHUDModeCustomView;
            HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Checkmark.png"]];
        }
        else{
            HUD.labelText = @"添加失败";
            HUD.mode = MBProgressHUDModeText;
        }
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        } completionBlock:^{
            [HUD removeFromSuperview];
            HUD = nil;
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
    }];
    
}

#pragma mark 上传订单方法（以后可以放在下一个界面中）
-(int)submitOrderForm:(OrderForm *)form{
    NSString *urlstr = [NSString stringWithFormat:@"%@orderform/addOrderForm?userID=%d&houseID=%d&arriveDate=%f&leaveDate=%f&personNum=%d&totlePrice=%f&status=%d&isComment=%d",kHTTPHome,form.userID,form.houseID,form.arriveDate,form.leaveDate,form.personNum,form.totlePrice,form.status,form.isComment];
//    NSLog(@"%@",urlstr);
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    
    NSData *data = [request responseData];
    if (data == nil) {
        NSLog(@"submit orderform------data为空");
    }
    NSDictionary *dic = [jd objectWithData:data];
    int result = [[dic objectForKey:@"result"] intValue];
    return result;
}

#pragma mark 选择到达日期动作
- (IBAction)chooseArriveDate:(UIButton *)sender{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    
    if (!calendarVC) {
        calendarVC = [[CalendarViewController alloc] init];
    }
    
    double now = kGetCurrentTime;
    //计算应显示的天数
    int shouldShowDays = (int)(self.house.houseExpirationdate - now) / kOneDaySeconds;
    
    if ([self.arriveButton.titleLabel.text isEqualToString:@"选择日期"]) {
        
        //第一个数字是要在日历上显示的天数，第二个是一开始被选中的日期，为空是表示当前日期
        calendarVC.calendarMonth = [self getMonthArrayOfDayNumber:shouldShowDays ToDateforString:nil];
    }
    else{
        //将被选中的日期设为arriveButton上的日期
        calendarVC.calendarMonth = [self getMonthArrayOfDayNumber:shouldShowDays ToDateforString:self.arriveButton.titleLabel.text];
    }
    
    [calendarVC.collectionView reloadData];//刷新

    
    __block VOLBookHouseViewController *blockSelf = self;
    //设置回调方法
    calendarVC.calendarblock = ^(CalendarDayModel *model){
        
//        NSLog(@"\n---------------------------");
//        
//        
//        NSLog(@"年----%u",model.year);
//        NSLog(@"月----%u",model.month);
//        NSLog(@"日----%u",model.day);
//        NSLog(@"星期---%u",model.week);
        
        
        //将日历上选的日期转化成NSDate，再变成double
        NSDate *date = [formatter dateFromString:[model toString]];
        //将date转化成double存入orderForm
        blockSelf->orderForm.arriveDate = [date timeIntervalSince1970];
        
        //设置arriveButton与leaveButton上面的文字
        [sender setTitle:[NSString stringWithFormat:@"%@",[model toString] ]forState:UIControlStateNormal];
        if (blockSelf->orderForm.leaveDate == 0|| blockSelf->orderForm.arriveDate >= blockSelf->orderForm.leaveDate) {
            double tomorrow = [date timeIntervalSince1970] + kOneDaySeconds;
            //将date转化成double存入orderForm
            blockSelf->orderForm.leaveDate = tomorrow;
            [blockSelf->_leaveButton setTitle:[formatter stringFromDate:kTransformToDate(tomorrow)] forState:UIControlStateNormal];
        }
        
        //显示入住天数Label
        blockSelf->days = (int)(blockSelf->orderForm.leaveDate - blockSelf->orderForm.arriveDate) / kOneDaySeconds;
        blockSelf->_daysLabel.text = [NSString stringWithFormat:@"共%d晚",blockSelf->days];
        blockSelf->_daysLabel.hidden = NO;
        //显示总价View
//        blockSelf->orderForm.totlePrice = blockSelf->orderForm.personNum * blockSelf->days * blockSelf->_house.housePrice;
//        blockSelf->_priceLabel.text = [NSString stringWithFormat:@"￥%.1f",blockSelf->orderForm.totlePrice];
        if (blockSelf.house.houseType == 0) {
            blockSelf->orderForm.totlePrice = blockSelf->days * blockSelf->_house.housePrice;
            blockSelf->_priceLabel.text = [NSString stringWithFormat:@"￥%.1f",blockSelf->orderForm.totlePrice];
        }else{
            blockSelf->orderForm.totlePrice = blockSelf->orderForm.personNum * blockSelf->days * blockSelf->_house.housePrice;
            blockSelf->_priceLabel.text = [NSString stringWithFormat:@"￥%.1f",blockSelf->orderForm.totlePrice];
        }
        blockSelf->_priceView.hidden = NO;
        //显示预订按钮
        blockSelf->bookBtn.hidden = NO;
    };
    
    
    //将日历界面显示出来
    [self presentViewController:calendarVC animated:YES completion:nil];
}

#pragma mark 选择离开日期动作
-(IBAction)chooseLeaveDate:(UIButton *)sender{
    NSLog(@"leave");
    if (orderForm.arriveDate == 0) {
        HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        
        HUD.labelText = @"请先选择到达日期";
        HUD.mode = MBProgressHUDModeText;
        
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        } completionBlock:^{
            [HUD removeFromSuperview];
            HUD = nil;
        }];
        return;
    }
    
//    double tomorrow = orderForm.arriveDate + kOneDaySeconds;
//    //计算应显示的天数
//    int shouldShowDays = (int)(self.houseExpirationdate - tomorrow) / kOneDaySeconds;

    double now = kGetCurrentTime;
    //计算应显示的天数
    int shouldShowDays = (int)(self.house.houseExpirationdate - now) / kOneDaySeconds;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    

    
    //第一个数字是要在日历上显示的天数，第二个是一开始被选中的日期，为空是表示当前日期
    calendarVC.calendarMonth = [self getMonthArrayOfDayNumber:shouldShowDays ToDateforString:self.leaveButton.titleLabel.text];
    
    [calendarVC.collectionView reloadData];//刷新
    
    __block VOLBookHouseViewController *blockSelf = self;
    //设置回调方法
    calendarVC.calendarblock = ^(CalendarDayModel *model){
        
//        NSLog(@"\n---------------------------");
//        
//        
//        NSLog(@"年----%u",model.year);
//        NSLog(@"月----%u",model.month);
//        NSLog(@"日----%u",model.day);
//        NSLog(@"星期---%u",model.week);
        
        
        //将日历上选的日期转化成NSDate，再变成double
        NSDate *date = [formatter dateFromString:[model toString]];
        blockSelf->orderForm.leaveDate = [date timeIntervalSince1970];
        
        if (blockSelf->orderForm.leaveDate <= blockSelf->orderForm.arriveDate) {
            
            blockSelf->HUD = [[MBProgressHUD alloc] initWithView:blockSelf.view];
            [blockSelf.view addSubview:blockSelf->HUD];
            
            blockSelf->HUD.labelText = @"离开日期不能早于到达日期";
            blockSelf->HUD.mode = MBProgressHUDModeText;
            [blockSelf->HUD showAnimated:YES whileExecutingBlock:^{
                sleep(1);
            } completionBlock:^{
                [blockSelf->HUD removeFromSuperview];
                blockSelf->HUD = nil;
            }];
            
            return;
        }
        
        [sender setTitle:[NSString stringWithFormat:@"%@",[model toString] ]forState:UIControlStateNormal];
        //显示入住天数Label
        blockSelf->days = (int)(blockSelf->orderForm.leaveDate - blockSelf->orderForm.arriveDate) / kOneDaySeconds;
        blockSelf->_daysLabel.text = [NSString stringWithFormat:@"共%d晚",blockSelf->days];
        //显示总价View
        if (blockSelf.house.houseType == 0) {
            blockSelf->orderForm.totlePrice = blockSelf->days * blockSelf->_house.housePrice;
            blockSelf->_priceLabel.text = [NSString stringWithFormat:@"￥%.1f",blockSelf->orderForm.totlePrice];
        }else{
            blockSelf->orderForm.totlePrice = blockSelf->orderForm.personNum * blockSelf->days * blockSelf->_house.housePrice;
            blockSelf->_priceLabel.text = [NSString stringWithFormat:@"￥%.1f",blockSelf->orderForm.totlePrice];
        }
    };
    
    //将日历界面显示出来
    [self presentViewController:calendarVC animated:YES completion:nil];
    
}
#pragma mark 增加/减少入住人数
- (IBAction)changePersonNum:(UIButton *)sender {
    
    if (sender.tag == 50) {//减少
        orderForm.personNum--;
        self.personNumField.text = [NSString stringWithFormat:@"%d位房客",orderForm.personNum];
        
    }
    if (sender.tag == 51) {//增加
        orderForm.personNum++;
        self.personNumField.text = [NSString stringWithFormat:@"%d位房客",orderForm.personNum];
    }
    
    if (orderForm.personNum > 1) {
        self.subButton.enabled = YES;
    }else{
        self.subButton.enabled = NO;
    }
    
    if (orderForm.personNum < self.house.housePersons) {
        self.addButton.enabled = YES;
    }else{
        self.addButton.enabled = NO;
    }

    //根据房屋类型计算价格
    if (self.house.houseType == 0) {
        orderForm.totlePrice = days * self.house.housePrice;
        self.priceLabel.text = [NSString stringWithFormat:@"￥%.1f",orderForm.totlePrice];

    }else{
        orderForm.totlePrice = orderForm.personNum * days * self.house.housePrice;
        self.priceLabel.text = [NSString stringWithFormat:@"￥%.1f",orderForm.totlePrice];
    }
    
}

#pragma mark - 逻辑代码初始化

//获取时间段内的天数数组
- (NSMutableArray *)getMonthArrayOfDayNumber:(int)day ToDateforString:(NSString *)todate
{
    NSDate *today = [NSDate date];
    //被选中的日期
    NSDate *selectdate  = [NSDate date];
    
    if (todate) {
        
        selectdate = [selectdate dateFromString:todate];
        
    }
    
    calendarVC.Logic = [[CalendarLogic alloc]init];
    
    return [calendarVC.Logic reloadCalendarView:today selectDate:selectdate  needDays:day];
}


#pragma mark - 代理方法

#pragma mark - 异步请求代理方法
#pragma mark 请求成功方法
-(void)requestFinished:(ASIHTTPRequest *)request{

    NSData *data = [request responseData];
    if (data == nil) {
        NSLog(@"bookHouse------data为空");
        return;
    }
    
    NSDictionary *dic = [jd objectWithData:data];
    
    NSArray *array = [dic objectForKey:@"date"];
    //遍历数组，添加数据到bookedDate
    for (NSDictionary *obj in array) {
        VOLDateCellModel *model = [VOLDateCellModel dateCellModelWithArrivtDate:[[obj objectForKey:@"arrive_date"] doubleValue] leaveDate:[[obj objectForKey:@"leave_date"] doubleValue]];
        [bookedDate addObject:model];
    }
    
    //遍历完成后刷新tableView
    
    if (bookedDate.count == 0) {

        self.dateTableView.tableHeaderView.frame = CGRectMake(0, 0, self.dateTableView.frame.size.width, 44);
        self.dateTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.dateTableView reloadData];
    }
    else{
        [self.dateTableView reloadData];
    }
    
    
}

#pragma mark 请求失败方法
-(void)requestFailed:(ASIHTTPRequest *)request{
    NSLog(@"bookHouse-----请求失败");
}

#pragma mark - UITextField代理
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return NO;
}

#pragma mark - UITableView DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return bookedDate.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"dateCell";
    UITableViewCell *cell = [self.dateTableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
    }
    
    //配置cell
    cell.textLabel.textColor = kThemeColor;
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.font = [UIFont fontWithName:@"System" size:15];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    VOLDateCellModel *model = bookedDate[indexPath.row];
    
    NSDate *startDate = kTransformToDate(model.arriveDate);
    NSDate *endDate = kTransformToDate(model.leaveDate);
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];

    cell.textLabel.text = [NSString stringWithFormat:@"%@   至   %@",[formatter stringFromDate:startDate],[formatter stringFromDate:endDate]];
    
    return cell;
}

#pragma mark 行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.dateTableView deselectRowAtIndexPath:indexPath animated:YES];
}


@end






